<template>
  <ContentWrap>
    <el-form
      v-show="showSearch"
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="90px"
      class="-mb-15px"
    >
      <el-form-item label="应聘岗位" prop="post">
        <el-cascader
          v-model="queryParams.post"
          :options="postOptions"
          :props="postProps"
          :show-all-levels="false"
          clearable
          filterable
          class="!w-220px"
          placeholder="请选择岗位"
        />
      </el-form-item>
      <el-form-item label="面试时间" prop="interviewTime">
        <el-date-picker
          v-model="interviewTimeRange"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-320px"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="邀约人" prop="inviter">
        <CascaderUser v-model="queryParams.inviter" class="!w-220px" clearable/>
      </el-form-item>
      <el-form-item label="应聘渠道" prop="channels">
        <el-input
          v-model="queryParams.channels"
          placeholder="请输入渠道"
          clearable
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status" v-if="selectedStatus=='ALL'">
        <el-select v-model="queryParams.statusList" placeholder="请选择状态" multiple filterable clearable>
          <el-option label="未到面（待到面）" value="0"/>
          <el-option label="未到面（取消到面）" value="6"/>
          <el-option label="已到面（未跟进）" value="1"/>
          <el-option label="已到面（不通过）" value="2"/>
          <el-option label="已到面（待定）" value="7"/>
          <el-option label="已到面（待入职）" value="3"/>
          <el-option label="已到面（未入职）" value="4"/>
          <el-option label="已到面（已入职）" value="5"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>


    <el-tabs
      v-model="selectedStatus"
      class="status-tabs mb-10px"
      type="card"
      stretch
    >

      <el-tab-pane
        v-for="item in statusOptions"
        :key="item.value"
        :name="item.value"
      >
        <template #label>
          <div class="status-tab__label">
            <Icon :icon="item.icon" class="status-tab__icon"/>
            <span class="status-tab__text">{{ item.panelName }}</span>
            <el-tag
              :type="item.tagType"
              size="small"
              effect="light"
              class="status-tab__tag"
            >
              {{ item.label }}
            </el-tag>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane name="ALL">
        <template #label>
          <div class="status-tab__label">
            <Icon icon="ep:collection" class="status-tab__icon"/>
            <span class="status-tab__text">全部</span>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>


    <div class="flex flex-wrap items-center justify-between gap-10px mb-10px">
      <div class="flex flex-wrap gap-10px">
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          plain-->
        <!--          @click="openForm('create')"-->
        <!--          v-hasPermi="['hr:recruit-interview:create']"-->
        <!--        >-->
        <!--          <Icon icon="ep:plus" class="mr-5px" />-->
        <!--          新增-->
        <!--        </el-button>-->
        <el-button
          type="primary"
          @click="openRegister"
          v-hasPermi="['hr:recruit-interview:create']"
        >
          <Icon icon="ep:edit-pen" class="mr-5px"/>
          登记
        </el-button>
        <!--        <el-button-->
        <!--          type="danger"-->
        <!--          plain-->
        <!--          :disabled="!checkedIds.length"-->
        <!--          @click="handleDeleteBatch"-->
        <!--          v-hasPermi="['hr:recruit-interview:delete']"-->
        <!--        >-->
        <!--          <Icon icon="ep:delete" class="mr-5px" />-->
        <!--          批量删除-->
        <!--        </el-button>-->
        <el-button
          type="success"
          plain
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['hr:recruit-interview:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :stripe="true"
      :border="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="姓名" prop="name" min-width="120"/>
      <el-table-column label="应聘岗位" prop="post" min-width="160" show-overflow-tooltip/>
      <el-table-column label="应聘渠道" prop="channels" min-width="140" show-overflow-tooltip/>
      <el-table-column label="邀约人" prop="inviter" min-width="120" show-overflow-tooltip/>
      <el-table-column label="面试时间" min-width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.interviewTime) }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="面试结果" prop="interviewResult" min-width="140" show-overflow-tooltip />-->
      <el-table-column label="跟进结果" prop="trailResult" min-width="180" show-overflow-tooltip/>
      <el-table-column label="录用情况" min-width="150">
        <template #default="{ row }">
          {{ row.whetherToHire || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="约定入职" min-width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.agreeDate) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="120">
        <template #default="{ row }">
          <el-tag v-if="findInterviewStatus(row.status)"
                  :type="findInterviewStatus(row.status)!.tagType">
            {{ findInterviewStatus(row.status)!.label }}
          </el-tag>
          <span v-else>{{ row.status || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" prop="urgentPhone" min-width="140" show-overflow-tooltip/>
      <el-table-column label="创建时间" min-width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="120">
        <template #default="{ row }">
          <div class="flex items-center gap-2">
            <el-button
              v-if="selectedStatus === 'ALL'"
              type="danger"
              link
              v-hasPermi="['hr:recruit-interview:delete']"
              :disabled="!canOperateInterview(row)"
              @click="handleCommand(row, 'delete')"
            >
              <Icon icon="ep:delete" class="mr-5px" />
              删除
            </el-button>

            <div v-if="row.status === '0'">
              <el-dropdown @command="handleCommand(row, $event)">
                <el-button type="primary" link>
                  更多
                  <el-icon class="el-icon--right">
                    <arrow-down/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="updateRegister" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:edit" class="mr-5px" />
                      修改登记
                    </el-dropdown-item>
                    <el-dropdown-item command="completeInfo" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:document" class="mr-5px" />
                      完善资料
                    </el-dropdown-item>
                    <el-dropdown-item command="followUp" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:bell" class="mr-5px" />
                      未到面跟进
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <div v-else-if="row.status === '1'">
              <el-dropdown @command="handleCommand(row, $event)">
                <el-button type="primary" link>
                  更多
                  <el-icon class="el-icon--right">
                    <arrow-down/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="completeInfo" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:document" class="mr-5px" />
                      完善资料
                    </el-dropdown-item>
                    <el-dropdown-item command="printResume" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:printer" class="mr-5px" />
                      打印简历
                    </el-dropdown-item>
                    <el-dropdown-item command="interviewFollowUp" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:promotion" class="mr-5px" />
                      面试跟进
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <div v-else-if="row.status === '3'">
              <el-dropdown @command="handleCommand(row, $event)">
                <el-button type="primary" link>
                  更多
                  <el-icon class="el-icon--right">
                    <arrow-down/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="completeInfo" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:document" class="mr-5px" />
                      完善资料
                    </el-dropdown-item>
                    <el-dropdown-item command="entryFollowUp" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:bell" class="mr-5px" />
                      未入职跟进
                    </el-dropdown-item>
                    <el-dropdown-item command="confirmEntry" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:check" class="mr-5px" />
                      确认入职
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <div v-else>
              <el-dropdown @command="handleCommand(row, $event)">
                <el-button type="primary" link>
                  更多
                  <el-icon class="el-icon--right">
                    <arrow-down/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="view">
                      <Icon icon="ep:view" class="mr-5px" />
                      查看
                    </el-dropdown-item>
                    <el-dropdown-item command="edit" v-hasPermi="['hr:recruit-interview:update']" :disabled="!canOperateInterview(row)">
                      <Icon icon="ep:edit" class="mr-5px" />
                      完善资料
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <RecruitInterviewForm ref="formRef" @success="getList"/>
  <RecruitInterviewDetailDialog ref="detailRef"/>
  <RecruitInterviewRegisterDialog ref="registerRef" @success="handleRegisterSuccess"/>
  <RecruitInterviewFollowUpDialog ref="followUpRef" @success="getList"/>
  <RecruitInterviewPrintDialog ref="printRef"/>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import type {FormInstance} from 'element-plus'
import download from '@/utils/download'
import {handleTree} from '@/utils/tree'
import {type RecruitInterview, RecruitInterviewApi} from '@/api/business/hr/recruit/interview'
import {type RecruitPost, RecruitPostApi} from '@/api/business/hr/recruit/post'
import RecruitInterviewForm from './RecruitInterviewForm.vue'
import RecruitInterviewDetailDialog from './components/RecruitInterviewDetailDialog.vue'
import RecruitInterviewRegisterDialog from './components/RecruitInterviewRegisterDialog.vue'
import RecruitInterviewFollowUpDialog from './components/RecruitInterviewFollowUpDialog.vue'
import RecruitInterviewPrintDialog from './components/RecruitInterviewPrintDialog.vue'
import {findInterviewStatus, INTERVIEW_STATUS_OPTIONS} from '@/views/business/hr/recruit/constants'
import {checkPermi} from '@/utils/permission'
import {useUserStore} from '@/store/modules/user'

interface RecruitPostCascaderNode extends RecruitPost {
  value: string
  label: string
  isLeaf?: boolean
  children?: RecruitPostCascaderNode[]
}

defineOptions({name: 'HrRecruitInterview'})

const {t} = useI18n()
const message = useMessage()

const showSearch = ref(true)
const loading = ref(false)
const exportLoading = ref(false)
const list = ref<RecruitInterview[]>([])
const total = ref(0)
const selectedStatus = ref<'ALL' | string>('ALL')
const interviewTimeRange = ref<string[]>([])
const checkedIds = ref<number[]>([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  post: undefined as string | undefined,
  name: undefined as string | undefined,
  inviter: undefined as string | undefined,
  channels: undefined as string | undefined,
  status: undefined as string | undefined,
  statusList: undefined as string[] | undefined,
})

const queryFormRef = ref<FormInstance>()

const postOptions = ref<RecruitPostCascaderNode[]>([])
const postProps = {
  value: 'post',
  label: 'post',
  emitPath: false,
  checkStrictly: true
}

const statusOptions = INTERVIEW_STATUS_OPTIONS.filter(item => item.showPanel == true)

const formatDateTime = (val?: string | null) => {
  if (!val) {
    return '-'
  }
  const parsed = dayjs(val)
  return parsed.isValid() ? parsed.format('YYYY-MM-DD HH:mm') : val
}

const buildParams = () => {
  const params: Record<string, any> = {
    ...queryParams
  }
  if (interviewTimeRange.value.length === 2) {
    params.interviewTime = [...interviewTimeRange.value]
  } else {
    delete params.interviewTime
  }
  if (params.status === undefined || params.status === null || params.status === '') {
    delete params.status
  }
  return params
}

const getList = async () => {
  loading.value = true
  try {
    const data = await RecruitInterviewApi.getRecruitInterviewPage(buildParams())
    list.value = data?.list ?? []
    total.value = data?.total ?? 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  interviewTimeRange.value = []
  queryParams.post = undefined
  queryParams.name = undefined
  queryParams.inviter = undefined
  queryParams.channels = undefined
  selectedStatus.value = 'ALL'
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleRowCheckboxChange = (records: RecruitInterview[]) => {
  checkedIds.value = records.map((item) => item.id!).filter((id): id is number => !!id)
}

const handleDelete = async (id?: number) => {
  if (!id) return
  try {
    await message.delConfirm()
    await RecruitInterviewApi.deleteRecruitInterview(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch (error) {
    if (error) {
      console.warn('删除失败', error)
    }
  }
}

const handleDeleteBatch = async () => {
  if (!checkedIds.value.length) {
    return
  }
  try {
    await message.delConfirm()
    await RecruitInterviewApi.deleteRecruitInterviewList(checkedIds.value)
    message.success(t('common.delSuccess'))
    checkedIds.value = []
    await getList()
  } catch (error) {
    if (error) {
      console.warn('批量删除失败', error)
    }
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await RecruitInterviewApi.exportRecruitInterview(buildParams())
    download.excel(data, '面试记录.xlsx')
  } catch (error) {
    if (error) {
      console.warn('导出失败', error)
    }
  } finally {
    exportLoading.value = false
  }
}

const formRef = ref<InstanceType<typeof RecruitInterviewForm>>()
const detailRef = ref<InstanceType<typeof RecruitInterviewDetailDialog>>()
const registerRef = ref<InstanceType<typeof RecruitInterviewRegisterDialog>>()
const followUpRef = ref<InstanceType<typeof RecruitInterviewFollowUpDialog>>()
const printRef = ref<InstanceType<typeof RecruitInterviewPrintDialog>>()

const openForm = (type: 'create' | 'update', id?: number) => {
  formRef.value?.open(type, id)
}

const openDetail = (row: RecruitInterview) => {
  if (!row.id) return
  detailRef.value?.open(row.id)
}

const openRegister = () => {
  registerRef.value?.open()
}

const openRegisterForm = (type: 'create' | 'update', id?: number) => {
  if (type === 'update' && id) {
    registerRef.value?.open('update', id)
  } else {
    registerRef.value?.open('create')
  }
}


const handleRegisterSuccess = async () => {
  await getList()
}

// 下拉菜单操作处理
const handleCommand = (row: RecruitInterview, command: string) => {
  switch (command) {
    case 'updateRegister':
      openRegisterForm('update', row.id)
      break
    case 'completeInfo':
      openForm('update', row.id)
      break
    case 'followUp':
      // 未到面跟进操作
      handleNoRegister(row)
      break
    case 'printResume':
      // 打印简历操作
      handlePrintResume(row)
      break
    case 'interviewFollowUp':
      // 面试跟进操作
      handleInterviewFollowUp(row)
      break
    case 'entryFollowUp':
      // 未入职跟进操作
      handleEntryFollowUp(row)
      break
    case 'confirmEntry':
      // 确认入职操作
      handleConfirmEntry(row)
      break
    case 'view':
      openDetail(row)
      break
    case 'edit':
      openForm('update', row.id)
      break
    case 'delete':
      handleDelete(row.id)
      break
  }
}

watch(selectedStatus, (status) => {
  if (status === 'ALL') {
    queryParams.status = undefined
    queryParams.statusList = undefined
  } else {
    queryParams.status = status
    queryParams.statusList = undefined

  }
  handleQuery()
})

const loadPostOptions = async () => {
  try {
    const data = await RecruitPostApi.getRecruitPostList({})
    const tree = handleTree(data || [], 'id', 'parentId') as RecruitPostCascaderNode[]
    const markLeaf = (nodes: RecruitPostCascaderNode[]) => {
      nodes.forEach((node) => {
        node.value = node.post || `${node.id}`
        node.label = node.post || node.dept || '-'
        if (node.children && node.children.length > 0) {
          markLeaf(node.children as RecruitPostCascaderNode[])
          node.isLeaf = false
        } else {
          node.isLeaf = true
        }
      })
      return nodes
    }
    postOptions.value = markLeaf(tree)
  } catch (error) {
    console.warn('岗位数据获取失败', error)
  }
}

onMounted(async () => {
  await loadPostOptions()
  await getList()
})

const handleNoRegister = (row: RecruitInterview) => {
  message.prompt('请输入跟进结果', '未到面跟进').then(({value}) => {
    if (!row.id) return
    const form: RecruitInterview = {
      id: row.id,
      trailResult: value,
      status: '6' // 未到面状态
    }
    RecruitInterviewApi.updateRecruitInterview(form).then(res => {
      message.success('操作成功')
      getList()
    }).catch(() => {
      message.error('操作失败')
    })
  }).catch(() => {
    // 用户取消操作
  })
}

const handleInterviewFollowUp = (row: RecruitInterview) => {
  if (!row.id) return
  followUpRef.value?.open(row)
}

const handlePrintResume = (row: RecruitInterview) => {
  printRef.value?.open(row)
}

const handleEntryFollowUp = (row: RecruitInterview) => {
  message.prompt('请输入跟进结果', '未入职跟进').then(({value}) => {
    if (!row.id) return
    const form: RecruitInterview = {
      id: row.id,
      trailResult: value,
      status: '4' // 未入职状态
    }
    RecruitInterviewApi.updateRecruitInterview(form).then(res => {
      message.success('操作成功')
      getList()
    }).catch(() => {
      message.error('操作失败')
    })
  }).catch(() => {
    // 用户取消操作
  })
}

const handleConfirmEntry = (row: RecruitInterview) => {
  message.confirm('确认该候选人已入职吗？', '确认入职').then(() => {
    if (!row.id) return
    const form: RecruitInterview = {
      id: row.id,
      status: '5' // 已入职状态
    }
    RecruitInterviewApi.updateRecruitInterview(form).then(res => {
      message.success('操作成功')
      getList()
    }).catch(() => {
      message.error('操作失败')
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 获取当前用户信息
const userStore = useUserStore()
const currentUser = userStore.getUser

// 判断用户是否有权限操作该面试记录
const canOperateInterview = (row: RecruitInterview) => {
  // 如果有管理员权限，则可以操作所有记录
  if (checkPermi(['hr:recruit-interview:admin'])) {
    return true
  }
  // 否则只能操作邀约人是自己的记录
  return row.inviter == currentUser.id
}

</script>

<style scoped lang="scss">
.status-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 12px;
    border-bottom: none;
  }

  :deep(.el-tabs__nav) {
    border: none;
    background-color: transparent;
    display: flex;
    gap: 8px;
  }
}

.status-tab__label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 0 4px;
}

.status-tab__icon {
  font-size: 16px;
  color: var(--el-color-primary);
}

.status-tab__text {
  font-weight: 600;
}

.status-tab__tag {
  margin-left: 2px;
}

.status-tabs :deep(.el-tabs__item) {
  border: none;
  border-radius: 10px;
  padding: 10px 14px;
  background: var(--el-color-info-light-9);
  color: var(--el-text-color-regular);
  transition: all 0.25s ease;
  box-shadow: none;
}

.status-tabs :deep(.el-tabs__item:hover) {
  background: rgba(64, 158, 255, 0.12);
  color: var(--el-color-primary);
}

.status-tabs :deep(.el-tabs__item.is-active) {
  background: linear-gradient(135deg, #409eff 0%, #2f7bfd 100%);
  color: #fff;
  box-shadow: 0 8px 16px rgba(64, 158, 255, 0.2);
}

.status-tabs :deep(.el-tabs__item.is-active) .status-tab__icon {
  color: #fff;
}

.status-tabs :deep(.el-tabs__item.is-active) .status-tab__tag {
  --el-tag-text-color: #fff;
  --el-tag-bg-color: rgba(255, 255, 255, 0.12);
  --el-tag-border-color: transparent;
}
</style>
